package com.gviiii.baiduai.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Properties;

public class PropertiesUtil {

    private static ClassLoader classLoader;

    public static String CLASSPATH_HOME;

    static {
        classLoader = PropertiesUtil.class.getClassLoader();
        try {
            CLASSPATH_HOME=Paths.get(Objects.requireNonNull(classLoader.getResource("")).toURI()).toString();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param src
     * @return
     */
    public static BufferedReader loadPropertiesByClasspath(String src){
        Path path=null;
        try {
             path= getClasspathPath(src);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        return getBufferedReader(path);
    }

    /**
     * @param dir
     * @param src
     * @return
     */
    public static BufferedReader loadPropertiesByFileSystem(String dir,String src){
        Path path=null;
        try {
            if (FileUtil.exists(Paths.get(dir, src))) {
                path=Paths.get(dir, src);
            }else {
                throw new FileNotFoundException(" 配置文件未找到");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return getBufferedReader(path);
    }

    /**
     * @param s
     * @return
     * @throws URISyntaxException
     */
    private static Path getClasspathPath(String s) throws URISyntaxException {
        return Paths.get(Objects.requireNonNull(classLoader.getResource(s)).toURI());
    }

    /**
     * @param path
     * @return
     */
    private static BufferedReader getBufferedReader(Path path) {
        BufferedReader bufferedReader=null;
        if (FileUtil.exists(path)){
            try {
                bufferedReader= Files.newBufferedReader(path, Charset.forName("UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bufferedReader;
    }

    /**
     * @return
     */
    public static Properties getProperties(){
        return new Properties();
    }
}
